const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CompressionPlugin = require("compression-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const fs = require("fs");

function generateHtmlPlugins() {
  const modulesDir = path.resolve(__dirname, "src");
  const htmlFiles = fs
    .readdirSync(modulesDir)
    .filter((file) => file.endsWith(".html"));

  return htmlFiles.map((file) => {
    return new HtmlWebpackPlugin({
      template: path.join(modulesDir, file),
      filename: file,
      inject: "body",
      minify: {
        removeComments: true,
        collapseWhitespace: true,
      },
    });
  });
}

module.exports = {
  entry: "./src/index.js",  // 入口文件
  output: {
    filename: "bundle.js",  // 固定的输出文件名
    path: path.resolve(__dirname, "dist"),
    clean: true, // 每次构建时清空输出目录
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: "babel-loader",
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
    ],
  },
  plugins: [
    ...generateHtmlPlugins(),
    new MiniCssExtractPlugin({
      filename: "assets/css/[name].[contenthash].css",
    }),
    new CompressionPlugin({
      algorithm: "gzip",
      test: /\.(js|css|html|svg)$/,
      threshold: 10240,
      minRatio: 0.8,
    }),
    new CopyWebpackPlugin({
      patterns: [
        { from: "src/assets", to: "assets" }, // 确保复制 assets 文件夹
      ],
    }),
  ],
  mode: "production",
};
